﻿using System;

namespace SmartSite.Frame
{
    public sealed class Crc
    {
        /// <summary>
        /// 校验和
        /// </summary>
        /// <param name="pucSendBuf"></param>
        /// <param name="usLen"></param>
        /// <returns></returns>
        public static UInt16 Calculate(byte[] pucSendBuf, UInt16 usLen)
        {
            if (pucSendBuf == null)
                throw new ArgumentNullException(nameof(pucSendBuf));

            UInt16 usCrc = 0xFFFF;

            for (UInt16 i = 0; i < usLen; i++)
            {
                usCrc ^= (UInt16)pucSendBuf[i];
                for (UInt16 j = 0; j < 8; j++)
                {
                    if ((usCrc & 1) != 0)
                    {
                        usCrc >>= 1;
                        usCrc ^= 0xA001;
                    }
                    else
                    {
                        usCrc >>= 1;
                    }
                }
            }

            return usCrc;
        }
    }
}
